using System.Collections.Generic;
using System.IO;
using mock_ehr_lib.Model.OrderEntry;
using Newtonsoft.Json;
using System.Linq;
using System;

namespace mock_ehr_lib.Data
{
    public class JsonOrderRepository : IOrderRepository
    {
        private List<Order> _orders;

        public JsonOrderRepository(string filename)
        {
            initialize(filename);
        }

        /// <summary>
        /// Parse a json file with orders
        /// </summary>
        /// <param name="filename">Absolute or relative path to json file</param>
        void initialize(string filename)
        {
            if (!File.Exists(filename)) throw new FileNotFoundException("Patient JSON repository file not found.");
            var jsonFile = File.ReadAllText(filename);
            _orders = JsonConvert.DeserializeObject<List<Order>>(jsonFile);
            foreach(var order in _orders)
            {
                order.OrderID = Guid.NewGuid().ToString();
            }
        }

        public IEnumerable<Order> GetOrdersByPatientID(int ID)
        {
            return _orders.Where(i => i.PatientID == ID);
        }

        public void SubmitOrder(Order order)
        {
            _orders.Add(order);
        }
    }
}